package com.deli.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.deli.springboot.entity.Comment;
import com.deli.springboot.entity.ResultDo;
import com.deli.springboot.entity.ResultList;
import com.deli.springboot.service.CommentServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


/**
 * 评论查询和新增
 */
@RestController
public class CommentController {

    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    @Autowired
    private CommentServiceImpl commentService;

    /**
     * 通过图书id查询评论列表
     *
     * @param bookId 书id
     * @return
     */
    @RequestMapping(value = "comment/find")
    public String findByBid(@RequestParam(value = "book_id") Long bookId) {
        ResultList<Comment> resultList = new ResultList();
        if (null == bookId && bookId < 0) {
            resultList.setErrorDescription("输入的图书id：" + bookId + " 有误");
            return JSON.toJSONString(resultList);
        }
        Comment comment = new Comment();
        comment.setBookId(bookId);
        List<Comment> CommentList = commentService.findByExample(comment);
        if (null != CommentList && CommentList.size() > 0) {
            resultList.setDataList(CommentList);
            return JSON.toJSONString(resultList);
        }
        resultList.setErrorDescription("搜索不到该评论");
        return JSON.toJSONString(resultList);
    }

    /**
     * 新增评论
     *
     * @param comment 评论对象的json字符串
     * @return
     */
    @RequestMapping(value = "comment/add")
    public String add(@RequestParam(value = "comment") Comment comment) {
        logger.info("go to CommentController addMethod comment param is " + comment);
        //Comment commentPojo = JSON.parseObject(comment, Comment.class);
        ResultDo<Integer> result = new ResultDo();

        if (null != comment && "" != JSON.toJSON(comment)) {
            comment.setStatus(1);//有效状态
            int add = commentService.add(comment);
            if (add <= 0) {
                result.setSuccess(false);
                result.setErrorDescription("添加评论失败");
                return JSON.toJSONString(result);
            } else {
                result.setSuccess(true);
                return JSON.toJSONString(result);
            }
        }
        result.setSuccess(false);
        result.setErrorDescription("输入的评论信息有误");
        return JSON.toJSONString(result);
    }
}

